<?php

    global $user_ID, $wpdb, $current_user;
    
    get_currentuserinfo();
    
    //is_user_logged_in()
    if($current_user->ID <= 0 || $user_ID <=0 ){              
        wp_redirect_to('/wp-admin/');
        exit;
    } 
    $post_id = $_GET['bs_id'];
    
    if($_POST['btnSubmit']){
        
        if($_POST['hId'] <=0 && $_GET['c_id'] <=0) {
            $sql = "INSERT INTO ".$wpdb->prefix."coupons ( user_id, start_date, end_date, code,headline,description,business_id, approved )
                            VALUES (".$user_ID.",".strtotime($_POST['start_date']).",".strtotime($_POST['end_date']).",
                                        '".addslashes($_POST['field_code'])."','".addslashes($_POST['field_headline'])."',
                                        '".addslashes($_POST['Description'])."',".$_POST['category'].",0)";
            $wpdb->query($sql);
            
            $sql = "SELECT * FROM ".$wpdb->prefix."posts p
                    INNER JOIN ".$wpdb->prefix."company c ON c.user_id = p.post_author
                    WHERE p.ID=".$_POST['category'];
            $db = $wpdb->get_results($sql);
            
            //coupon_create($db[0]->post_title, $db[0]->name, $_POST['field_headline'],$_POST['Description'], $_POST['field_code']);
            error_('Addnew OK!','confirm');
            wp_redirect_to('?page=accm&tabmenu=coupons',2);
            
        } else {
            $c_id = ($_GET['c_id']>0)?$_GET['c_id']:0;
            
            $sql = "UPDATE ".$wpdb->prefix."coupons SET
                                user_id = ".$_POST['uId'].",
                                start_date = ".strtotime($_POST['start_date']).", 
                                end_date = ".strtotime($_POST['end_date']).", 
                                code='".addslashes($_POST['field_code'])."',
                                headline='".addslashes($_POST['field_headline'])."',
                                description='".addslashes($_POST['Description'])."',
                                approved='".$_POST['approved']."',
                                business_id = ".$_POST['category']." WHERE id=".$c_id;
            $wpdb->query($sql);
            if($_POST['approved']==1) {
                //send mail
                send_approved($_POST['uId']);
            }
            error_('Your data has been updated successfully!','confirm');
            //wp_redirect_to('?page=accm&tabmenu=coupons',2);
        }
        
    }
    
    if($_POST['btnDelete']) {
        $_IDs = $_POST['chk_item'];     
        $_IDs[] = 0;
          
        $sql = "UPDATE ".$wpdb->prefix."coupons SET approved = -1 WHERE id in (".implode($_IDs).")";
        $wpdb->query($sql);
        //error_('Delete OK!','confirm');
        wp_redirect_to('?page=accm&tabmenu=coupons',2);
    }
    
     if($_POST['btnApprove']) {
        $_IDs = $_POST['chk_item']; 
        foreach($_IDs as $key => $id){
            $sql = "SELECT user_id FROM ".$wpdb->prefix."coupons WHERE id=".$id;
            $db = $wpdb->get_results($sql);
            $user_id = $db[0]->user_id;
            $sql = "UPDATE ".$wpdb->prefix."coupons SET approved = 1 WHERE id=".$id;
            $wpdb->query($sql);
            send_approved($user_id);
        }
        //error_('Approve OK!','confirm');
        wp_redirect_to('?page=accm&tabmenu=coupons',2); 
    }
    
    ?>
    
    <div id="business_lists">
        <!--<div id="tabs">
            <ul>
                <li <?php print ($_GET['tab'] ==''?'class="selected"':'');?>>
                    <a href="?page=accm&tabmenu=coupons">Coupon Management</a>
                </li>
                <li <?php print ($_GET['tab'] =='update'?'class="selected"':'');?>>Addnew/Update</li>
            </ul>
        </div>-->
        <?php if($_GET['tab']=='') { 
            
                $status = ($_POST['status']!='')? $_POST['status'] : ($_GET['status']!=''?$_GET['status']:'');                
            ?>
        <div id="table-company">
            <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" id="frmBusinessListing"  name="frmBusinessListing" enctype="multipart/form-data">
                <div class="tab-header" style="width: 640px;">
                    Select: <select id="status" name="status">
                                <option value="">-All-</option>
                                <option value="1" <?php print ($status=='1'?'selected="selected"':'');?>>Approved</option>
                                <option value="0" <?php print ($status=='0'?'selected="selected"':'');?>>Pending</option>
                                <option value="-1" <?php print ($status=='-1'?'selected="selected"':'');?>>Deleted</option>
                           </select>
                           <input class="button" type="submit" value="Apply" id="btnApply" name="btnApply" />
						   <?php 
							$is_admin = ( $current_user->caps[administrator]==1 )? 1 : 0;
							if (!$is_admin) { ?>
							<input type="button" value="Add New" id="btnCouponAddnew" name="btnCouponAddnew" class="button">
						   <?php } ?>
                    <br />
                   <?php
						if (!$is_admin) {
							error_('*Note: If you make any changes to your coupon information, it will require admin approval before it can be displayed on the web site.');
						}
					?> 
                </div>         
				<?php
				
					// Sorting
					$arr_opt = array();
					$arr_opt = array_merge($_GET);
					$sql_order = '';
					
					if(!isset($_GET['sort_by']) || $_GET['sort_by'] == '' ) {
						$arr_opt['sort_by'] = 'approved';
						$arr_opt['sort_dir'] = 'asc';	
					} 
					
					//build sql
					$sql_order .= ' ORDER BY ' . $arr_opt['sort_by'] . ' ' . $arr_opt['sort_dir'];
					
					unset($arr_opt['sort_by']);
					if($arr_opt['sort_dir'] == 'asc') {
						$arr_opt['sort_dir'] = 'desc';
					} else {
						$arr_opt['sort_dir'] = 'asc';
					}
					
					$status_sort_uri = '?';
				
					foreach(array_keys($arr_opt) as $opt) {
						$status_sort_uri .= $opt . '=' . $arr_opt[$opt] . '&';
					}
					
					$status_sort_uri .= 'sort_by=approved';
					
					// End Sorting
				?>
                <div class="header row" style="width: 640px;">
                    <div class="col2 col"><input type="checkbox" id="chk_all" name="chk_all" /></div>
                    <div class="col7 col">Code </div>  
                    <div class="col4 col" style="width: 265px;">Assigned to Business</div>                     	             
                    <div class="col7 col"><a href="<?php echo $status_sort_uri; ?>">Status</a></div>
                    <div class="col7 col">Details</div>
                </div>
                <?php
                   $post_status = ''; $status = '';
                   if($_POST['status']!='') {
                        $post_status = " WHERE  c.approved = '".$_POST['status']."'";
                        $status = $_POST['status'];
                   } else 
                    if($_GET['status'] )  {
                        $status = $_POST['status'];
                        $post_status = " WHERE  c.approved = '".$_GET['status']."'";
                    }
                   
                   $page_size = 15;
                   $current_page = ($_GET['pg'] >0)? $_GET['pg'] : 1;
                   $page = ($current_page - 1)*$page_size;
                   if($page < 0 ) $page = 1; 
                   $bs_posts = $wpdb->get_results("SELECT count(*) total  FROM ".$wpdb->prefix."coupons $post_status");
                   $i = 1;
                   $total_rec = $bs_posts[0]->total;
                   $total_page = (int)($bs_posts[0]->total/$page_size);
                   if($total_page < 1 ) 
                    $total_page = 1;
                   else
                   if($total_page*$page_size < $bs_posts[0]->total ) $total_page++;
                   $from_row = $page_size*($current_page-1) + 1;
                   $to_row  = $page_size*($current_page-1) + $page_size;
                   if($to_row > $total_rec) $to_row  = $total_rec;
                   
                   $sql = "SELECT c.*, p.post_title  FROM ".$wpdb->prefix."coupons c                                                   
                            INNER JOIN ".$wpdb->prefix."posts p ON p.ID = c.business_id
                            $post_status ";                                
							/* ORDER BY c.start_date LIMIT $page, $page_size"; */
                    $sql.= $sql_order . " LIMIT $page, $page_size";
                                                    
                   $bs_posts = $wpdb->get_results($sql);
                   
                   foreach($bs_posts as $post){
                ?>
                <div class="row" style="width: 640px;"> 
                    <div class="col2 col"><input class="chk_item" type="checkbox" id="chk_item<?php print $post->id; ?>" name="chk_item[]" value="<?php print $post->id; ?>" /></div>
                    <div class="col7 col"><?php print $post->code;?></div>
                    <div class="col4 col" style="width: 265px;"><?php print $post->post_title;?></div>
                    <div class="col7 col">
                        <?php if($post->approved==0) print '<font color=#bd000>Waiting for Approval</font>';
                              else  if($post->approved == -1) print '<font color=#bd000>Trash</font>';
                                else print 'Approved';
                        ?>
                    </div>
                    <div class="col7 col"><a href="?page=accm&tabmenu=coupons&tab=update&bs_id=<?php print $post->business_id;?>&c_id=<?php print  $post->id;?>">View</a></div>                
                </div>
                <?php $i++; } 
                    if($i == 1 )
                        print '<div style="float: left; width: 620px; text-align: center;" class="row col">No Coupon Found</div>';
                ?> 
                <div class="footer" style="width: 640px;">
                    <div class="paging">
                        <div class="left">Displaying <strong><?php print $from_row; ?></strong> - <strong><?php print $to_row; ?></strong> of <strong><?php print $total_rec;?> </strong></div>
                        <div class="right" style="width: 420px;">Go to: 
                         <?php for($p = 1; $p <= $total_page; $p++ ) { 
                            if($p==$current_page) { ?>
                            <a class="curent-page" href="#"><?php print $p;?></a>&nbsp;
                            <?php } else { ?> <a href="?page=accm&tabmenu=coupons&pg=<?php print $p;?>&status=<?php print $status;?>"><?php print $p;?></a><?php } ?>
                         <?php } ?>
                        </div>
                    </div> 
                    <div style="float:  left; padding: 10px;">
                        <input class="button" type="submit" id="btnApprove" name="btnApprove" value="Approve" />  
						<?php /*
                        <input class="button" type="submit" id="btnDeny" name="btnDeny" value="Deny" />                     
						*/ ?>
                        <input class="button" type="submit" id="btnDelete" name="btnDelete" value="Delete" />
                    </div>                   
                </div>
            </form>
        </div>
        <?php } 
            
            if($_GET['tab']=='update') {
                
                $start_date = $_POST['start_date'];
                $end_date = $_POST['end_date'];
                $field_code = $_POST['field_code'];
                $field_headline = $_POST['field_headline'];
                $Description = $_POST['Description'];
                $approved = $_POST['approved'];
                $user_id = $user_ID;
                if($_GET['c_id'] > 0 && $_POST['hId'] <= 0 ) {
                    $sql = "SELECT * FROM ".$wpdb->prefix."coupons 
                            WHERE id=".$_GET['c_id']; 
                    $db = $wpdb->get_results($sql);   
                    
                    $start_date = date('m/d/Y',$db[0]->start_date);
                    $end_date = date('m/d/Y',$db[0]->end_date);
                    $field_code = $db[0]->code;
                    $field_headline = $db[0]->headline;
                    $Description = $db[0]->description; 
                    $user_id =  $db[0]->user_id;       
                    $approved =  $db[0]->approved;                         
                }
                
                $sql = "select p.ID, p.post_title, t.name from ".$wpdb->prefix."posts p
                        inner join ".$wpdb->prefix."term_relationships tr  on p.ID = tr.object_id
                        inner join ".$wpdb->prefix."term_taxonomy tt on tt.term_taxonomy_id = tr.term_taxonomy_id
                        inner join ".$wpdb->prefix."terms t on t.term_id = tt.term_id
                        where p.post_type = 'businesslisting' and p.post_status = 'publish' and p.post_author =".$user_id;
                        
                $db = $wpdb->get_results($sql); 
                
                $select_business = '<select id="category" name="category">';
                $select_business .= '<option value="">--Select category --</option>';
                foreach($db as $post) {                  
                    $select_business .= '<option value="'.$post->ID.'" '.( ($_POST['bs_id']==$post->ID || $_GET['bs_id']==$post->ID)?"selected=selected":'').'>
                                        &nbsp;&nbsp;'.$post->name.' - '.$post->post_title.'&nbsp;&nbsp;</option>';
                }
                $select_business .= '</select>';  
                
                
                
         ?>
    <div id="business_lists_update">
        <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post" id="frmBusinessListing"  name="frmBusinessListing">
           <div class="form-item">
                <div class="left ">Published:</div>
                <div class="right" style="line-height: 35px;"> 
                <input type="radio" name="approved" <?php print ($approved==1?'checked=true':'')?> value="1" /> Yes 
                <input type="radio" name="approved" <?php print ($approved==0?'checked=true':'')?> value="0" /> No</div>
           </div>
           <div class="form-item">
                <div class="left ">Start Date <font color="#bd0000">*</font>: </div>
                <div class="right"><input value="<?php print $start_date;?>" type="text" id="start_date" name="start_date" class="input  required datetime" style="padding:5px;">     </div>
           </div>
           <div class="form-item">
                <div class="left ">End Date <font color="#bd0000">*</font>: </div>
                <div class="right"><input value="<?php print $end_date;?>" type="text" id="end_date" name="end_date" class="input  required datetime" style="padding: 5px;">     </div>
           </div>
           <div class="form-item">
                <div class="left ">Coupon Code:<font color="#bd0000">*</font>: </div>
                <div class="right"><input value="<?php print $field_code;?>" type="text" id="field_code" name="field_code" class="input  required" style="padding: 5px;"> &nbsp;<em>For Personal Use</em></div>
           </div>
           <div class="form-item">
                <div class="left ">Headline:<font color="#bd0000">*</font>: </div>
                <div class="right"><input value="<?php print $field_headline;?>" type="text" id="field_headline" name="field_headline" class="input  required" style="padding: 5px;"></div>
           </div>
           <div class="form-item">
                <div class="left ">Description: <font color="#bd0000">*</font>: </div>
                <div class="right"><textarea id="Description" maxlength="180" name="Description" rows="5" style="width: 100%;"><?php print $Description;?></textarea><br /><em>Max of 180 characters.</em></div>
           </div>
           <div class="form-item">
                <div class="left ">Business: <font color="#bd0000">*</font>: </div>
                <div class="right"><?php print $select_business; ?></div>
           </div>
           <div class="form-item">
                <div class="left ">&nbsp;
                    <input type="hidden" id="hId" name="hId" value="<?php print $_GET['c_id'];?>" />
                    <input type="hidden" id="uId" name="uId" value="<?php print $user_id;?>" />
                </div>
                <div class="right"><input value="Submit New Coupon" type="submit" id="btnSubmit" name="btnSubmit" class="button"></div>
           </div>
        </form>
    </div>
           <?php 
            }
        ?>
    </div>
